package cn.devzyh.oms.coms.express.service;

import cn.devzyh.oms.common.core.util.R;
import cn.devzyh.oms.coms.api.order.dto.OrderDTO;
import cn.devzyh.oms.coms.api.order.entity.OrderHeader;
import cn.devzyh.oms.coms.flow.context.FlowContext;
import cn.devzyh.oms.coms.flow.executor.FlowNode;
import cn.devzyh.oms.coms.order.service.OrderHeaderService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 匹配快递工作流节点
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MatchExpressNode implements FlowNode {

	private final ExpressService expressService;

	private final OrderHeaderService orderHeaderService;

	private static final String EXPRESS_CODE = "expressCode";

	@Override
	public R process(FlowContext ctx) {
		OrderDTO order = (OrderDTO) ctx.getMainCache();
		OrderHeader header = order.getHeader();

		R res = expressService.match(header);
		if (res.success()) {
			header.setExpressCode(res.getData().toString());
			LambdaUpdateWrapper<OrderHeader> wrapper = Wrappers.lambdaUpdate();
			wrapper.set(OrderHeader::getExpressCode, header.getExpressCode());
			wrapper.eq(OrderHeader::getId, header.getId());
			orderHeaderService.update(wrapper);
		}

		ctx.addResult(EXPRESS_CODE, header.getExpressCode());

		return res;
	}

}
